<template>
  <div class="more-operation-wrapper">
    <el-popover placement="top-start" :width="60" trigger="hover">
      <template #reference>
        <div class="operation-wrapper">
          <el-icon>
            <component is="MoreFilled" />
          </el-icon>
        </div>
      </template>
      <div class="operation-items">
        <div
          v-for="item in operationList"
          :key="item.id"
          @click="handleSelectItem(item)"
          class="item"
        >
          {{ item.label }}
        </div>
      </div>
    </el-popover>
    <el-dialog
      style="border-radius: 15px"
      v-model="historyVisible"
      width="90%"
      top="5vh"
      class="history-modal"
    >
      <template #header>
        <div class="" style="font-weight: 500">历史记录</div>
      </template>
      <el-divider content-position="center">仅展示30天的历史记录。</el-divider>
      <div class="content">
        <div class="folder-item-wrapper p-10">
          <Document
            disabled
            v-if="props.data.icon === 'Document' && initContent"
            v-model:title="props.data.title"
            :content="initContent"
          />
          <Diagram
            v-else-if="props.data.icon === 'FlowChart' && initContent"
            isSilentMode
            :data="initContent"
          />
          <MindMap
            v-else-if="props.data.icon === 'Xmind' && initContent"
            readonly
            :data="initContent"
          />
        </div>
        <el-table-v2
          :columns="columns"
          :data="dataSource"
          :row-class="rowClass"
          :width="400"
          :height="600"
        />
      </div>
      <!-- @end-reached="handleGetdata" -->
    </el-dialog>

    <el-dialog
      style="border-radius: 15px"
      v-model="setPwdVisible"
      width="40%"
      top="15vh"
      class="history-modal"
      destroy-on-close
      @close="resetForm(ruleFormRef)"
    >
      <template #header>
        <div class="" style="font-weight: 500; margin-bottom: 10px">
          设置阅读密码
        </div>
      </template>
      <div class="set-pwd">
        <el-form
          ref="ruleFormRef"
          style="max-width: 600px"
          :model="ruleForm"
          status-icon
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
          label-position="left"
        >
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="ruleForm.password"
              type="password"
              autocomplete="off"
            />
          </el-form-item>
          <el-form-item label="重复密码" prop="checkPass">
            <el-input
              v-model="ruleForm.checkPass"
              type="password"
              autocomplete="off"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetForm(ruleFormRef)">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <Modal v-model="deleteVisible" @confirm="deleteNote"></Modal>
  <MoveNoteModal
    v-model="moveVisible"
    :appendParentData="props.data"
    isEdit
  ></MoveNoteModal>
  <CreateShareModal
    v-model="shareVisible"
    :rows="props.data"
  ></CreateShareModal>
  <LabelModal
    v-model:visible="labelVisible"
    :rowData="props.data"
    :callback="updateBreadcrumb"
    edit
  />
</template>
<script setup>
import { ref, h, reactive, computed, inject, watch, nextTick } from 'vue'
import { ElButton, ElIcon } from 'element-plus'
import Document from './document.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Diagram from '@/components/logic-flow-mvp/components/Diagram.vue'
import useUserStore from '@/stores/user.js'
import useNoteStore from '@/stores/note'
import { storeToRefs } from 'pinia'
import Modal from './deleteNoteModal.vue'
import { useRouter } from 'vue-router'
import MoveNoteModal from './moveNoteModal.vue'
import CreateShareModal from './CreateShareModal.vue'
import LabelModal from './labelModal.vue'
import MindMap from '@/components/mind-map/Index.vue'
import { asBlob } from 'html-docx-js-typescript'
import { downloadFile } from '@/utils/tools.ts'
import { enumNoteSpace } from '@/enum/note'
import {
  httpCreateNotePwd,
  httpAddNoteReadPwd,
  httpDeleteNoteReadPwd,
  httpDeleteNoteBook,
  httpGetAllNoteVersion,
  httpGetNoteDetailFromVersion,
  httpRecoverNoteHistory,
  httpCreateNote,
  httpStopShareLink,
  httpDeleteShareToMyNote,
  httpPubblishNoteToNoteSpace,
  httpUnpublishFromNoteSpace,
} from '@/api/note'

const props = defineProps({
  data: {
    Object,
    default: () => {},
  },
  lock: Boolean,
  initLock: Boolean,
})

const userStore = useUserStore()
const router = useRouter()
const noteState = useNoteStore()
const { info } = storeToRefs(userStore)
const { noteData } = storeToRefs(noteState)
const setPwdVisible = ref(false)
const deleteVisible = ref(false)
const moveVisible = ref(false)
const historyVisible = ref(false) // 历史记录弹窗
const dataSource = ref([])
const initContent = ref('')
const shareVisible = ref(false) // 创建分享弹窗
const labelVisible = ref(false) // 关联标签

const columns = [
  {
    key: 'version',
    title: '版本',
    width: 200,
    cellRenderer: (data) =>
      h(
        'div',
        {
          onClick: () => handleToggleNoteVersion(data),
        },
        [
          h('div', {}, data.rowData.version),
          h('div', {}, new Date(data.rowData.created_at).toLocaleString()),
        ],
      ),
  },
  {
    key: 'handle',
    title: '操作',
    width: 200,
    align: 'center',
    cellRenderer: (data) =>
      //  // 返回两个按钮
      //  h(
      //     ElButton,
      //     { onClick: () => handleDelete(data), type: 'danger', icon: 'Delete' },
      //     { default: () => '删除' }
      //   ),
      h(
        'div',
        {
          class: 'flex-center',
          style:
            'display:flex;align-items:center;justify-content:center;gap:4px',
        },
        [
          h(
            ElButton,
            {
              onClick: () => handleSaveNewNote(data),
              type: 'text',
            },
            { default: () => '保存为新笔记' },
          ),
          h(
            ElButton,
            {
              onClick: () => handleRecoverNote(data),
              type: 'text',
              // icon: 'Delete',
            },
            { default: () => '恢复' },
          ),
        ],
      ),
  },
]

const rowClass = ({ rowIndex }) => {
  if (rowIndex % 10 === 5) {
    return 'bg-red-100'
  } else if (rowIndex % 10 === 0) {
    return 'bg-blue-200'
  }
  return ''
}
const staticOperationList = ref([
  { id: 7, label: '分享中' },
  { id: 8, label: '取消分享' },
  { id: 1, label: '历史记录' },
  { id: 2, label: '阅读密码' },
  { id: 3, label: '移动到' },
  { id: 4, label: '删除' },
  { id: 5, label: '导出word' },
  { id: 6, label: '创建分享' },
  { id: 10, label: '发布到笔记空间' },
  { id: 11, label: '关联标签' },
])
const otherList = ref([
  { id: 1, label: '历史记录' },
  { id: 4, label: '删除' },
  { id: 5, label: '导出word' },
  { id: 9, label: '保存到我的笔记' },
])
const updateBreadcrumb = inject('updateBreadcrumb')
const operationList = computed(() => {
  if (!props.lock && info.value.read_password && props.initLock) {
    staticOperationList.value.find((x) => x.id === 2).label = '移除阅读密码'
  }
  if (info.value.user_info_id === props.data.user_info_id) {
    let status = props.data.note_place_status
    let obj = staticOperationList.value.find((x) => x.id === 10)
    if (obj) {
      if (
        enumNoteSpace.unpubblish !== status &&
        enumNoteSpace.fail !== status
      ) {
        obj.label = '取消发布'
      } else {
        obj.label = '发布到笔记空间'
      }
    }
    if (props.data.icon === 'Document') {
      // 分享中
      if (props.data.set) {
        return staticOperationList.value.filter((x) => x.id !== 6)
      } else {
        // 新建分享  info.value.user_info_id  == props.data.user_info_id
        return staticOperationList.value.filter((x) => {
          return x.id !== 7 && x.id !== 8
        })
      }
    } else {
      if (props.data.set) {
        return staticOperationList.value.filter((x) => x.id !== 6 && x.id !== 5)
      } else {
        return staticOperationList.value.filter(
          (x) => x.id !== 7 && x.id !== 8 && x.id !== 5,
        )
      }
    }
  } else {
    // 不是我的笔记 只能查看历史记录 删除 导出word
    if (props.data.set?.authority === 1) {
      return otherList.value.filter((item) => item.id !== 1)
    } else {
      return otherList.value.filter((item) => item.id !== 1)
    }
  }
})

const ruleFormRef = ref()
const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (ruleForm.checkPass !== '') {
      if (!ruleFormRef.value) return
      ruleFormRef.value.validateField('checkPass')
    }
    callback()
  }
}
const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== ruleForm.password) {
    callback(new Error('密码不一致!'))
  } else {
    callback()
  }
}

const ruleForm = reactive({
  password: '',
  checkPass: '',
})

const rules = reactive({
  password: [{ validator: validatePass, trigger: 'blur' }],
  checkPass: [{ validator: validatePass2, trigger: 'blur' }],
})
const emit = defineEmits(['update'])

const handleToggleNoteVersion = async (version) => {
  const res = await httpGetNoteDetailFromVersion({
    history_id: version.rowData.id,
  })
  if (res) {
    const { list } = res
    const { note_content } = list[0]
    const { icon } = props.data
    let content = note_content
    if (icon === 'FlowChart') {
      await nextTick(() => {
        initContent.value = content
          ? JSON.parse(content)
          : { nodes: [], edges: [] }
      })
    } else if (icon === 'Xmind') {
      await nextTick(() => {
        initContent.value = content
          ? JSON.parse(content)
          : {
              data: {
                text: '根节点',
              },
              children: [],
            }
      })
    } else {
      await nextTick(() => {
        initContent.value = content
      })
    }
  }
}
const handleSaveNewNote = async (data) => {
  //保存为新笔记
  const res = await httpGetNoteDetailFromVersion({
    history_id: data.rowData.id,
  })
  let note_content = res.list[0].note_content
  let content
  if (res) {
    if (data.rowData.icon === 'FlowChart') {
      content = note_content
        ? note_content
        : JSON.stringify({ nodes: [], edges: [] })
    } else if (data.rowData.icon === 'Xmind') {
      content = note_content
        ? note_content
        : JSON.stringify({
            data: {
              text: '根节点',
            },
            children: [],
          })
    } else {
      content = note_content
    }
    const result = await httpCreateNote({
      folder_id: 0,
      title: '',
      content,
      icon: props.data.icon,
      label_id_list: [],
    })
    if (result) {
      ElMessage.success('新笔记保存成功')
      await noteState.getFolderListData()
    }
  }
}
const handleRecoverNote = async (data) => {
  const res = await httpRecoverNoteHistory({
    history_id: data.rowData.id,
  })
  if (res) {
    ElMessage.success('笔记恢复成功')
    emit('update')
    // noteState.getFolderListData()
  }
}
watch(
  () => historyVisible.value,
  async () => {
    if (props.data) {
      if (props.data.icon === 'FlowChart') {
        await nextTick(() => {
          initContent.value = props.data.content
            ? JSON.parse(props.data.content)
            : { nodes: [], edges: [] }
        })
      } else if (props.data.icon === 'Xmind') {
        await nextTick(() => {
          initContent.value = props.data.content
            ? JSON.parse(props.data.content)
            : {
                data: {
                  text: '根节点',
                },
                children: [],
              }
        })
      } else {
        await nextTick(() => {
          initContent.value = props.data.content
        })
      }
    }
    if (historyVisible.value) {
      const res = await httpGetAllNoteVersion({
        fd_id: props.data.id,
      })
      if (res.list.length) {
        dataSource.value = res.list
      }
    }
  },
)

const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
  ruleForm.password = ''
  ruleForm.checkPass = ''
  setPwdVisible.value = false
}

const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      console.log('submit!')
      const res = await httpCreateNotePwd({
        password: ruleForm.password,
      })
      console.log('res', res)
      if (res) {
        const result = await httpAddNoteReadPwd({ fd_id: props.data.id })
        await userStore.getInfo(true)
        console.log('result', result, info.value)
        emit('update')
        setPwdVisible.value = false
      }
    } else {
      console.log('error submit!')
    }
  })
}

const deleteNote = async () => {
  // 是自己的笔记
  if (info.value.user_info_id === props.data.user_info_id) {
    let res = await httpDeleteNoteBook({
      detail_id: props.data.id,
    })
    if (res) {
      ElMessage.success('删除成功')
      await noteState.getFolderListData()
      await noteState.getShortCutList()
      await router.push('/file/note/' + noteData.value[0]?.id || '')
    } else {
      ElMessage.error('删除失败')
    }
  }
  //  else {
  //   // 不是本人笔记
  //   const result = await httpDeleteShareToMyNote({
  //     fd_id: appendParentData.value.id,
  //   })
  //   if (result) {
  //     ElMessage.success('删除成功')
  //     router.push('/file/share/')
  //   } else {
  //     ElMessage.error('删除失败')
  //   }
  // }
}
const handleSelectItem = async (item) => {
  const { id, user_info_id, content, icon, title, note_place_status } =
    props.data
  if (item.id === 1) {
    // 历史记录

    historyVisible.value = true
  } else if (item.id === 2) {
    if (info.value.read_password) {
      if (!props.lock && props.initLock) {
        // 移除阅读密码
        httpDeleteNoteReadPwd({ fd_id: id }).then((res) => {
          if (res) {
            emit('update')
          }
        })
        return
      } else {
        await httpAddNoteReadPwd({ fd_id: id })
      }
      emit('update')
    } else {
      setPwdVisible.value = true
    }
  } else if (item.id === 3) {
    moveVisible.value = true
  } else if (item.id === 4) {
    // 删除
    // 不是本人的笔记info.value.user_info_id ==user_info_id
    if (user_info_id !== info.value.user_info_id) {
      ElMessageBox.confirm('确认删除分享吗?', '删除分享', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const result = await httpDeleteShareToMyNote({
            fd_id: id,
          })
          if (result) {
            ElMessage.success('删除成功')
            await router.push('/file/share/')
          } else {
            ElMessage.error('删除失败')
          }
        })
        .catch(() => {})
    } else {
      // 是本人的笔记
      deleteVisible.value = true
    }
  } else if (item.id === 5) {
    // 导出word
    const data = await asBlob(content, {
      orientation: 'portrait',
      margins: {
        top: 2160,
        right: 1440,
        bottom: 2160,
        left: 1440,
        header: 720,
        footer: 720,
        gutter: 0,
      },
    })
    if (icon === 'Document') {
      downloadFile(data, title)
    }
  } else if (item.id === 6) {
    // 创建分享
    shareVisible.value = true
    // updateBreadcrumb()
  } else if (item.id === 7) {
    // 分享中
    shareVisible.value = true
  } else if (item.id === 8) {
    stopShareNoteLink()
  } else if (item.id === 9) {
    // 保存为我的笔记
    const res = await httpCreateNote({
      folder_id: 0,
      title: '',
      content: content,
      icon: icon,
      label_id_list: [],
    })
    if (res) {
      ElMessage.success('保存到我的笔记成功')
      await noteState.getFolderListData()
    } else {
      ElMessage.error('保存失败')
    }
  } else if (item.id === 10) {
    // 发布到笔记空间
    let status = note_place_status
    console.log('status', status)
    if (enumNoteSpace.unpubblish === status || enumNoteSpace.fail === status) {
      ElMessageBox.confirm('发布的笔记将公开', '确认发布到笔记空间吗?', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const res = await httpPubblishNoteToNoteSpace({
            note_id: id,
          })
          if (res) {
            emit('update')
            ElMessage.success('发布成功')
          } else {
            ElMessage.error('发布失败')
          }
        })
        .catch(() => {})
    } else {
      ElMessageBox.confirm('取消发布笔记', '确认取消发布到笔记空间吗?', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const res = await httpUnpublishFromNoteSpace({
            note_id: id,
          })
          if (res) {
            emit('update')
            ElMessage.success('取消成功')
          } else {
            ElMessage.error('取消失败')
          }
        })
        .catch(() => {})
    }
  } else if (item.id === 11) {
    // 关联标签
    labelVisible.value = true
  }
}

const stopShareNoteLink = () => {
  ElMessageBox.confirm('确认取消分享?', '取消分享', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    const res = await httpStopShareLink({
      fd_id: props.data.id,
    })
    if (res) {
      ElMessage({
        type: 'success',
        message: '取消分享成功',
      })
      await updateBreadcrumb()
    }
  })
  // .catch(() => {
  //   ElMessage({
  //     type: 'info',
  //     message: '取消分享失败',
  //   })
  // })
}
</script>
<style scoped lang="scss">
:deep(.el-dialog__header) {
  padding-bottom: 0 !important;
}

.operation-wrapper {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  border: 1px solid #ccc;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;

  &:hover {
    color: #409eff;
    border-color: #409eff;
  }
}

.operation-items {
  display: flex;
  flex-direction: column;
  justify-content: center;

  .item {
    height: 24px;
    cursor: pointer;

    &:hover {
      color: #409eff;
      background-color: #fafafa;
    }
  }
}

.content {
  display: flex;
  height: 70vh;
}

.folder-item-wrapper {
  border: 1px solid #ccc;
  overflow-y: auto;
  // width: 70%;
  width: 50%;
  flex: 1;
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 10px;
  height: 10px;
}

/* 滑块样式 */
::-webkit-scrollbar-thumb {
  background-color: #9f9f9f;
  border-radius: 10px;
}

/* 滚动条轨道样式 */
::-webkit-scrollbar-track {
  background-color: #fcfcfc;
  border-radius: 10px;
}

.flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 4px;
}
</style>
